package com.cbd.basic.algorithm.sort;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

/**
 * 冒泡排序
 * 核心思想：每一轮两两比较，将最大的元素放到最右边
 * 时间复杂度：O(n²)
 */
@Slf4j
public class BubbleSort {
    public static void main(String[] args) {
        //int[] array = {64, 34, 25, 12, 22, 11};
        int[] array = {1, 2, 3, 7, 5};

        log.info("before sorted array = {}", JSON.toJSONString(array));
        for (int i = 0; i < array.length - 1; i++) {
            boolean swapped = false;
            for (int j = 0; j < array.length - 1 - i; j++) {
                log.info("比较两个元素位置：{} - {}", j, j + 1);
                if (array[j] > array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                    swapped = true;
                }
            }
            if (!swapped) {
                break;
            }
        }
        log.info("after sorted array = {}", JSON.toJSONString(array));
    }
}
